package tool

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"myserver/model"
	"os"
	"time"
)

var MyDb *MyOrm

type MyOrm struct {
	Db *gorm.DB
}

func GetDB() *MyOrm {
	return MyDb
}

func OrmEngine(cfg *Config) (*MyOrm, error) {
	database := cfg.Database
	conn := database.User + ":" + database.Password + "@tcp(" + database.Host + ":" + database.Port + ")/" + database.DbName + "?charset=" + database.Charset
	db, err := gorm.Open(mysql.Open(conn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		return nil, err
	}
	log.Println("日志在ormEngine中输出的")
	err = db.AutoMigrate(&model.User{})
	if err != nil {
		log.Println(err)
	}
	err = db.AutoMigrate(&model.Region{}, &model.Family{}, &model.House{}, &model.Reservation{}, &model.ResourceType{}, &model.Role{})
	db.AutoMigrate(&model.OneTitle{}, &model.TwoTitle{})
	if err != nil {
		log.Println(err)
	}
	orm := new(MyOrm)
	orm.Db = db
	MyDb = orm
	return orm, nil
}

func GetLog() logger.Interface {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             1 * time.Nanosecond, // 慢 SQL 阈值
			LogLevel:                  logger.Silent,       // 日志级别
			IgnoreRecordNotFoundError: true,                // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,               // 禁用彩色打印
		},
	)
	return newLogger
}
